package com.wn.sk.order.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wn.sk.feign.dto.OrderPayDto;
import com.wn.sk.order.contants.OrderConstant;
import com.wn.sk.order.entity.Order;
import com.wn.sk.order.entity.OrderItem;
import com.wn.sk.order.service.IOrderItemService;
import com.wn.sk.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author yellow Docter
 * @date 2022 -11-11
 * @desc
 *  死信队列的消费
 */
@Component
@Slf4j
public class OrderDeadQueueConsumer {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *  可以 把 mq中发送的字符串信息直接转成 对象  OrderPayDto
     *
     * @param orderPayDto
     */
    @RabbitListener(
            queues = "dead_order_queue"
    )
    public void handlerMsg(@Payload OrderPayDto orderPayDto){

        //把 order 修改
        String orderSn = orderPayDto.getOrderSn();

        LambdaQueryWrapper<Order> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Order::getOrderSn, orderSn);
        Order order = orderService.getOne(queryWrapper);

        if (order.getStatus() .equals(OrderConstant.ORDER_NORMAL_TYPE)){ //修改状态

            //改成无效状态
            order.setStatus(OrderConstant.ORDER_STATUS_INVALID);
            orderService.updateById(order);
            // redis中的库存恢复


            Integer promotionId = orderPayDto.getPromotionId();
            Integer productId = orderPayDto.getProductId();
            String key = "product:sk:stock:" + promotionId;
            stringRedisTemplate.opsForList().leftPush(key,String.valueOf(productId));
        }

        log.info("消息消费成功 ....");
    }

}
